<?php

namespace Lib;

use Exception;
use Sdk\lib\Core;

class Cos {

	const UploadLimit = 100 * 1024;

	public static function __callStatic($name, $arguments) {
		return Core::RequestWit(__CLASS__, $name, $arguments, Core::Type_StaticMethod);
	}

	public static function Upload($f) {
		if (!file_exists($f)) {
			throw new Exception('plugin pack fail');
		}
		$size = filesize($f);
		if (!$size) {
			throw new Exception('plugin pack fail');
		}
		$md5 = md5_file($f);
		$fd = fopen($f, 'r');
		if (!$fd) {
			throw new Exception('plugin pack fail');
		}

		try {
			Core::RequestWit(__CLASS__, 'FileReceive',
				array(
					'file' => md5($f),
					'step' => 'start',
					'data' => array(
						'size' => $size,
						'md5' => $md5,
					)
				));
		} catch (Exception $e) {
			throw new Exception($e->getMessage(), $e->getCode());
		}

		$offset = 0;
		$step = 1;
		do {
			fseek($fd, $offset);
			$data = fread($fd, self::UploadLimit);
			try {
				Core::RequestWit(__CLASS__, 'FileReceive',
					array(
						'file' => md5($f),
						'step' => $step,
						'data' => base64_encode($data),
					));
			} catch (Exception $e) {
				throw new Exception($e->getMessage(), $e->getCode());
			}
			$offset += self::UploadLimit;
			$step++;
		} while ($offset < $size);
		@fclose($fd);

		try {
			$file = Core::RequestWit(__CLASS__, 'FileReceive',
				array(
					'file' => md5($f),
					'step' => 'end',
					'data' => '',
				));
		} catch (Exception $e) {
			throw new Exception($e->getMessage(), $e->getCode());
		}

		return Core::RequestWit(__CLASS__, __FUNCTION__,
			array('file' => $file));
	}

}